function varargout = CISNE(varargin)
% This file is part of CISNE.
%
%     CISNE is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     any later version.
%
%     CISNE is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with CISNE.  If not, see <http://www.gnu.org/licenses/>.

% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal

% Last Modified by GUIDE v2.5 29-Jun-2011 09:49:53

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @CISNE_OpeningFcn, ...
                   'gui_OutputFcn',  @CISNE_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
%trick to pass splashwindow to GUI
% varargin={varargin{:}, 'userData', s};
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before CISNE is made visible.
function CISNE_OpeningFcn(hObject, eventdata, handles, varargin)
set(handles.figure1,'Visible','off');
% Choose default command line output for CISNE
handles.output = hObject;
%s=get(handles.figure1,'UserData');
handles.CISNE_VERSION='0.9.9';

%splash init.
s=SplashScreen( 'Splashscreen',['images' filesep 'splash.png'],...
    'ProgressBar', 'on','ProgressPosition', 5,'ProgressRatio', 0.3 );
s.addText(5,16,'INTEGRATED SWAN ENVIROMENT','FontSize',15,'Color',[0 0 0.6]);
s.addText(330,35,['Ver. ' handles.CISNE_VERSION],...
    'FontSize',25,'Color',[0.2 0.2 0.5]);
s.addText( 15, 255, 'Loading Main Window', 'FontSize', 15, 'Color', 'white' );



%Software name and version!
CISNE_NAME=sprintf('CISNE %s Beta Release',...
    handles.CISNE_VERSION);
set(handles.figure1,'Name',CISNE_NAME);

handles.SWANPath=[];
% Initialize JIDE's usage within Matlab, needed by TreeWidget and
% GridWidget

com.mathworks.mwswing.MJUtilities.initJIDE;
handles.TreeWidget=TreeWidget(handles.TreePanel);
handles.DisplayWidget=DisplayWidget(handles.DisplayPanel);
handles.SetupWidget=SetupWidget(handles.SetupPanel);
loadOutParams(handles.TW_Output);
set(s,'ProgressRatio',0.6);
handles.mouseButtonDown=0;
set(handles.figure1,'WindowButtonDownFcn',@mouseButtonDown);
set(handles.figure1,'WindowButtonMotionFcn',@mouseMove);
set(handles.figure1,'WindowButtonUpFcn',@mouseButtonRelease);
handles.s=s;
% Update handles structure
guidata(hObject, handles);



% --- Outputs from this function are returned to the command line.
function varargout = CISNE_OutputFcn(hObject, eventdata, handles) 

% Get default command line output from handles structure
varargout{1} = handles.output;

%adding statusbar
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
warning('off','MATLAB:hg:JavaSetHGProperty');

jFrame = get(handles.figure1,'JavaFrame');
handles.jRootPane = [];
while isempty(handles.jRootPane)
    %i wonder why this is needed.... but without this, crashes.
    handles.jRootPane = jFrame.fFigureClient.getWindow;
end
handles.jStatusBar = com.mathworks.mwswing.MJStatusBar;
handles.jRootPane.setStatusBar(handles.jStatusBar);
handles.jStatusBar.setText('GUI Initialized...');
handles.jRootPane.setStatusBarVisible(1);

%adding progressbar to statusbar.
handles.jProgressBar = javax.swing.JProgressBar;
handles.jStatusBar.add(handles.jProgressBar,'West');  %left side.
handles.jProgressBar.setVisible(0);
set(handles.s,'ProgressRatio',0.8);
%adding icons to buttons.

fields=fieldnames(handles);
buttons=regexp(fields,'PB_');

for j=1:length(buttons)
    if ~isempty(buttons{j})
        data=...
         imread(fullfile('images',[regexprep(fields{j},'PB_','') '.png']));
        set(handles.(fields{j}),'CData',data);
    end
end
set(handles.s,'ProgressRatio',1);
%save handles data.
guidata(hObject,handles);
handles.s.delete();
set(handles.figure1,'Visible','on');

%%other functions go here.

% --- Executes on button press in PB_select.
function PB_select_Callback(hObject, eventdata,handles)
%selects a grid, or output item (point, line).
handles.DisplayWidget.setAction('select');



% --- Executes on button press in PB_edit.
function PB_edit_Callback(hObject, eventdata,handles)
%edit a computational grid, control point or control line.
handles.DisplayWidget.setAction('edit');

% --- Executes on button press in PB_zIn.
function PB_zIn_Callback(hObject, eventdata,handles)
setptr(handles.figure1,'glassplus');
handles.DisplayWidget.setAction('zoomIn');


% --- Executes on button press in PB_zOut.
function PB_zOut_Callback(hObject, eventdata,handles)
setptr(handles.figure1,'glassminus');
handles.DisplayWidget.setAction('zoomOut');

% --- Executes on button press in PB_zExtent.
function PB_zExtent_Callback(hObject, eventdata,handles)
handles.DisplayWidget.zoomExtent();

% --- Executes on button press in PB_ZArea.
function PB_zArea_Callback(hObject, eventdata,handles)
setptr(handles.figure1,'glass');
handles.DisplayWidget.setAction('zoomArea');

% --- Executes on button press in PB_addIGrid.
function PB_addIGrid_Callback(hObject, eventdata,handles)
%adds a new Input grid. Uses Dialog to get Grid Name and kind.
dlg=InputGridDlg('userData',handles.TreeWidget);
close(dlg);

% --- Executes on button press in PB_addCGrid.
function PB_addCGrid_Callback(hObject, eventdata,handles)
%adds a new Computational grid. Uses Dialog to get Grid Name.
dlg=CompGridDlg('userData',handles.TreeWidget);
close(dlg);


% --- Executes on button press in PB_addCPoint.
function PB_addCPoint_Callback(hObject, eventdata,handles)
persistent n;
if isempty(n)
n=1;
end
handles.TreeWidget.addControlPoint(['P' num2str(n)]);
n=n+1;

% --- Executes on button press in PB_addCLine.
function PB_addCLine_Callback(hObject, eventdata,handles)


%%%%%-----------------------------------------------------------%%%%%%


% --------------------------------------------------------------------
function SettingsMenu_Callback(hObject, eventdata, handles)
% hObject    handle to SettingsMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
dlg=SettingsDlg('userData',handles);


% --- Executes on selection change in LW_Cases.
function LW_Cases_Callback(hObject, eventdata, handles)
% hObject    handle to LW_Cases (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns LW_Cases contents as cell array
%        contents{get(hObject,'Value')} returns selected item from LW_Cases


% --- Executes during object creation, after setting all properties.
function LW_Cases_CreateFcn(hObject, eventdata, handles)
% hObject    handle to LW_Cases (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function loadOutParams(obj)
%hardcoded params from SWAN User Manual. UPDATE WITH NEW PARAMETERS!
params={'HSIGN', true; 'HSWELL', false; 'DIR', true; 'PDIR', false;...
    'TDIR', false; 'TM01', false; 'RTM01', false; 'RTP', false; ...
    'TPS', false; 'PER', false; 'RPER', false; 'TMM10', false; ...
    'RTMM10', false; 'TM02', false; 'FSPR', false; 'DSPR', false; ...
    'QP', false; 'DEPTH', false; 'WATLEV', false; 'BOTLEV', false; ...
    'VEL', false; 'FRCOEF', false; 'WIND', false; 'PROPAGAT', false;...
    'PROPXY',false; 'PROPTHETA', false; 'PROPSIGMA', false; ...
    'GENERAT', false; 'REDIST', false; 'REDQUAD', false; 'DISSIP',false;...
    'DISBOT', false; 'DISSURF', false; 'DISWCAP', false; 'DISVEG',false;...
    'RADSTR', false; 'QB', false; 'TRANSP', false; 'FORCE', false; ...
    'UBOT', false; 'URMS', false; 'TMBOT', false; 'WLEN', false; ...
    'STEEPNESS', false; 'BFI', false; 'NPLANTS', false; 'DHSIGN', false;...
    'DRTM01', false; 'LEAK', false; 'TIME', false; 'TSEC', false; ...
    'XP', true; 'YP', true; 'DIST', false; 'SETUP', false;};

set(obj,'Data',params);


% --- Executes on button press in PB_AddSCase.
function PB_AddSCase_Callback(hObject, eventdata, handles)
% hObject    handle to PB_AddSCase (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
child=AddSingleCase(handles);
close(child);

% --- Executes on button press in PB_AddCaseList.
function PB_AddCaseList_Callback(hObject, eventdata, handles)
% hObject    handle to PB_AddCaseList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
loadCasesFromList(handles);

% --- Executes on button press in PB_DelSCase.
function PB_DelSCase_Callback(hObject, eventdata, handles)
% hObject    handle to PB_DelSCase (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
item=get(handles.LW_Cases,'Value');
if item>0
cases=get(handles.LW_Cases,'String');
cases(item)=[];
set(handles.LW_Cases,'String',cases);
end

% --- Executes on button press in PB_DelCaseList.
function PB_DelCaseList_Callback(hObject, eventdata, handles)
% hObject    handle to PB_DelCaseList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.LW_Cases,'String','');


%%$ --- MENU CALLBACKS ---

% --------------------------------------------------------------------

% --------------------------------------------------------------------
function RunCasesMenu_Callback(hObject, eventdata, handles)
% hObject    handle to RunCasesMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%TODO: finish this command. Under linux works, same approach for windows
%should use another gui, at least to display process and some info.

 %T=evalc('!/home/jose/dev/SWAN/cisneSwan -input /home/jose/Documentos/Prueba_cisne/SWN/Linux001-H5T15D270Lvl0.swn');
% se trata de hacer un bucle para cada archivo de la carpeta SWN del proyecto
% y ejecutar el comando cisneSwan incluyendo el archivo que hay que ejecutar
% La salida la obtenemos en T, y con strfind(T,'Normal end of run') sabemos 
% si el resultado es ok o no. Si falla, paramos la ejecucion de SWAN y mostramos
% el error (errfile)

%for private use only. Lets consider that SWAN is under /home/jose/dev/SWAN
%SWANfolder='/home/jose/dev/SWAN'; %should be a setting value.

%make sure that we add SWANfolder just once to PATH!!
%path1 = getenv('PATH');
%path1 = [path1 ':' SWANfolder];
%setenv('PATH', path1);

set(handles.figure1,'Pointer','watch');
swan=handles.SWANPath;
swanpath=fileparts(swan);

path1 = getenv('PATH');
if isempty(strfind(path1,swanpath))
    path1 = [path1 ':' swanpath];
    setenv('PATH', path1);
end

projectdir=char(handles.SetupWidget.getValue('Project Folder'));

listaAux=dir(fullfile(projectdir,'SWN','*.swn')); 
m_listaCasos={listaAux.name};

if strfind(computer,'GLNX')    
    if ~exist(fullfile(swanpath,'cisneSwan'),'file')
        evalc(sprintf('!cp %s %s',...
            [pwd filesep 'extras' filesep 'cisneSwan'],swanpath));
    end
end

if (~isempty(m_listaCasos))
           
    set(handles.jProgressBar,'StringPainted','on','Minimum',0, 'Maximum',...
        length(m_listaCasos), 'Value',0);
    handles.jStatusBar.setText('Running SWAN Cases...');
    handles.jProgressBar.setValue(0);
    handles.jProgressBar.setVisible(1);
    
    for j=1:length(m_listaCasos)
        fName=fullfile(projectdir,'SWN',m_listaCasos{j});
        if strfind(computer,'WIN')
            %some rework needed under windows, so we can just copy and work
            %in actual path. (after all, we have swan in system path).
           evalc(sprintf('!copy %s %s',['"' fName '"'],...
               ['"' pwd filesep 'INPUT"']));
           T=evalc(sprintf('!%s',['"' swan '"']));
        else
            T=evalc(sprintf('!%s -input %s',fullfile(swanpath,...
                'cisneSwan'),fName));
        end
        if (~isempty(strfind(T,'Normal end of run')))
            handles.jProgressBar.setValue(j);
            %remove unwanted data (unwanted right now).
            delete('norm_end');
            delete('Errfile');
            delete('PRINT');
            delete('swaninit');
            delete('INPUT');
        else
            handles.jStatusBar.setText(sprintf('ERROR FOUND ON RUN NUMBER %i',j));
            break;
        end
    end
    handles.jStatusBar.setText('ALL SWAN CASES RUN.');

else
   handles.jStatusBar.setText('YOU MUST GENERATE SWAN FILES FIRST.'); 
end
set(handles.figure1,'Pointer','arrow');






% --------------------------------------------------------------------
function Untitled_2_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function LoadProjectMenu_Callback(hObject, eventdata, handles)
% hObject    handle to LoadProjectMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function SaveProjectMenu_Callback(hObject, eventdata, handles)
% hObject    handle to SaveProjectMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function QuitMenu_Callback(hObject, eventdata, handles)
% hObject    handle to QuitMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.TreeWidget.delete;
close(handles.figure1);

% --------------------------------------------------------------------
function DrawSptMenu_Callback(hObject, eventdata, handles)
% hObject    handle to DrawSptMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
child=DrawSpt();
close(child);

% --------------------------------------------------------------------
function DrawMeshMenu_Callback(hObject, eventdata, handles)
% hObject    handle to DrawMeshMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
child=DrawMesh();
close(child);

% --------------------------------------------------------------------
function AboutMenu_Callback(hObject, eventdata, handles)
% hObject    handle to AboutMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
AboutDlg('UserData',handles.CISNE_VERSION);

% --------------------------------------------------------------------
function CISNEHelpMenu_Callback(hObject, eventdata, handles)
% hObject    handle to CISNEHelpMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web(['file:///' pwd filesep 'doc' filesep 'CISNE-DOC.html'],'-helpbrowser');

% --------------------------------------------------------------------
function SWANHelpMenu_Callback(hObject, eventdata, handles)
% hObject    handle to SWANHelpMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web('http://swanmodel.sourceforge.net/online_doc/swanuse/swanuse.html');

% --------------------------------------------------------------------
function GenerateCasesMenu_Callback(hObject, eventdata, handles)
% hObject    handle to GenerateCasesMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
GenerateCases(handles);
